<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { downloadInvoice, useGetInvoiceRecordPage } from '@fl/api/member-api'
import { SearchForm, SearchTable } from '@fl/components'
import { downloadFileWithUrl } from '@fl/utils/fn'
import { treeFindLabel } from '@fl/utils/tree'
import { cloneDeep } from 'lodash-es'

import { INVOICE_STATUS, INVOICE_STATUS_OPTIONS, INVOICE_TYPE_OPTIONS } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: '/pages/invoice/invoice-record',
})

const initialState = {
    applyTime: '',
}
const state = ref(cloneDeep(initialState))

const searchConditions = ref(cloneDeep(initialState))
const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})
const getInvoiceRecordPageParams = computed(() => ({
    beginDate: searchConditions.value.applyTime?.[0],
    endDate: searchConditions.value.applyTime?.[1],
    page: tablePage.currentPage,
    size: tablePage.pageSize,
}))

const {
    data: invoiceRecordPageData,
    isLoading: isGetInvoiceRecordPageLoading,
    total: invoiceRecordTotal,
} = useGetInvoiceRecordPage(getInvoiceRecordPageParams)

// #region Form
const columns: PlusColumn[] = [
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            startPlaceholder: '请选择开始时间',
            type: 'datetimerange',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
        },
        label: '申请时间',
        prop: 'applyTime',
        valueType: 'date-picker',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}
// #endregion

// #region Table
const isTableLoading = computed(() => isGetInvoiceRecordPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 60 },
        { field: 'invoiceTitle', title: '发票抬头' },
        { field: 'invoicePrice', title: '发票金额(元)' },
        { field: 'bankAccount', title: '申请账号' },
        { field: 'invoiceType', formatter: formatInvoiceType, title: '类型', width: 170 },
        { field: 'createTime', title: '申请时间', width: 170 },
        { field: 'status', formatter: formatStatus, title: '开票状态', width: 100 },
        { slots: { default: 'operation' }, title: '操作', width: 200 },
    ],
})

function formatInvoiceType({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: INVOICE_TYPE_OPTIONS })
}

function formatStatus({ cellValue }) {
    return treeFindLabel({ targetValue: cellValue, treeData: INVOICE_STATUS_OPTIONS })
}

watchEffect(() => {
    tableData.value = cloneDeep(invoiceRecordPageData.value)
    tablePage.total = invoiceRecordTotal.value
})
// #endregion

// #region UI Listener
async function onDownloadBtnClick(row: any) {
    try {
        const data = await downloadInvoice(row.id)
        downloadFileWithUrl(data, `${row.invoiceTitle}-${treeFindLabel({ targetValue: row.invoiceType, treeData: INVOICE_TYPE_OPTIONS })}`)
    }
    catch (error) {
        console.log(error)
    }
}
// #endregion
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <SearchForm v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        />
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #operation="{ row }">
                <el-button v-if="row.status === INVOICE_STATUS.DONE"
                           class="!p-4 !text-#409EFF"
                           text
                           @click="onDownloadBtnClick(row)"
                >
                    下载
                </el-button>
            </template>
        </SearchTable>
    </el-card>
</template>
